package com.kcsj.servelt;

import com.kcsj.model.Order;
import com.kcsj.model.User;
import com.kcsj.service.OrderService;
import com.kcsj.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/admin/login")
public class AdminUserLoginServlet extends HttpServlet {
    private UserService uService = new UserService();

    private OrderService oService = new OrderService();

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String ue = request.getParameter("ue");
        String password = request.getParameter("password");
        User user = uService.login(ue, password);
        if (user == null) {
            request.setAttribute("failMsg", "学号、邮箱或者密码错误，请重新登录！");
            request.getRequestDispatcher("/admin/user_login.jsp").forward(request, response);
        } else {
            // 订单为空则判断是新用户,首页不推荐新品
            List<Order> list = oService.selectAll(user.getId());
            if (list.isEmpty()) {
                user.setIsnew(true);
            }

            request.getSession().setAttribute("user", user);
            if(user.isIsadmin()) {
                request.getRequestDispatcher("/admin/user_center.jsp").forward(request, response);
                return;
            }
            request.getRequestDispatcher("/user_center.jsp").forward(request, response);
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }
}
